package com.daiyang.lottery.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

@Configuration
public class RedisUtil {
    private final static Logger logger = LoggerFactory.getLogger(RedisUtil.class);
    /**
     * 1.RedisTemplate 是以byte[]的形式存储的，所以需要指定序列化器，不方便阅读
     * 2. StringRedisTemplate 是以String的形式存储的，所以不需要指定序列化器
     * 本次项目都是以String,String 存储的 所以使用StringRedisTemplate
     */
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 设置redis中的值
     * 长时间有效
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key, String value) {
        try {
            stringRedisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            logger.error("set redis (key: {} value: {}) error", key, value, e);
            return false;
        }
    }
    /**
     * 设置redis中的值
     * 时间有效
     * @param key
     * @param value
     * @param time 单位：秒
     * @return
     */
    public boolean set(String key, String value,Long time) {
        if(time ==null||time < 0){
            throw new RuntimeException( "time is null or time < 0");
        }
        try {
            stringRedisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            logger.error("set redis (key: {} value: {}) error", key, value, e);
            return false;
        }
    }
    public String get(String key) {
        try {
            return null == key ? null : stringRedisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            logger.error("get redis (key: {}) error", key, e);
            return null;
        }
    }
    public boolean delete(String ...key) {
        try {
             stringRedisTemplate.delete((Collection<String>)CollectionUtils.arrayToList(key));
            return true;
        }   catch (Exception e) {
            logger.error("delete redis (key: {}) error", key, e);
            return false;
        }
    }

    public boolean hasKey(String key) {
        try {
            return null != key && stringRedisTemplate.hasKey(key);
        }   catch (Exception e) {
            logger.error("hasKey redis (key: {}) error", key, e);
            return false;
        }
    }

}
